//
//  FCSearchRelationViewController.m
//  customerRelation_Example
//
//  Created by 陈文斌 on 2019/2/15.
//  Copyright © 2019 64912907. All rights reserved.
//

#import "FCSearchRelationViewController.h"
#import "FCRelationTableViewCell.h"
#import "FCCustomerRelationRequest.h"
#import "FCRelationListModel.h"
#import "FCRelationCompanyDetailViewController.h"
#import "CustomerRelationHeader.h"

@interface FCSearchRelationViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) UIView *searchContentView;
@property (nonatomic, strong) UITextField *searchTextField;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *relations;

@property (nonatomic, strong) UIImageView *navBarHairlineImageView;

@end

@implementation FCSearchRelationViewController
- (NSMutableArray<FCRelationModel *> *)relations{
    if (!_relations) {
        _relations = [NSMutableArray new];
    }
    return _relations;
}

- (void)setupUI{
    self.title = customerRelationLocaChanged(@"关系管理搜索", @"关系管理搜索");
    self.view.backgroundColor = FCBackColor;
    
    UIView *searchView = [[UIView alloc] init];
    [self.view addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.and.right.mas_equalTo(0);
        make.height.mas_equalTo(48);
    }];
    searchView.backgroundColor = [UIColor whiteColor];
    _searchContentView = [UIView new];
    [searchView addSubview:_searchContentView];
    [_searchContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(30);
    }];
    _searchContentView.backgroundColor = FCBackColor;
    _searchContentView.layer.cornerRadius = 4;
    UIImageView *searchIconImageView = [UIImageView new];
    [_searchContentView addSubview:searchIconImageView];
    [searchIconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(12);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
    searchIconImageView.image = customerRelationImageName(@"nav_ic_search_g");
    _searchTextField = [UITextField new];
    [_searchContentView addSubview:_searchTextField];
    [_searchTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchIconImageView.mas_right).mas_equalTo(6);
        make.right.mas_equalTo(-12);
        make.height.mas_equalTo(18);
        make.centerY.mas_equalTo(0);
    }];
    _searchTextField.delegate = self;
    _searchTextField.placeholder = customerRelationLocaChanged(@"global_general_search", @"搜索");
    _searchTextField.font = font13;
    _searchTextField.returnKeyType = UIReturnKeySearch;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(searchView.mas_bottom).mas_equalTo(0);
        make.left.and.right.mas_equalTo(0);
        make.bottom.mas_equalTo(FCTabbarSafeBottomMargin);
    }];
    [self setupTableView];
    
    [_searchTextField becomeFirstResponder];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navBarHairlineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    _navBarHairlineImageView.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _navBarHairlineImageView.hidden = NO;
}

#pragma mark - searchTF
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    [self.tableView.mj_header beginRefreshing];
    
    return YES;
}

#pragma mark - tableVIew

#define RelationCell @"FCRelationTableViewCell"

- (void)setupTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = FCBackColor;
    [self setExtraCellLineHidden:self.tableView];
    self.tableView.separatorStyle = UITableViewCellEditingStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([FCRelationTableViewCell class]) bundle:nil] forCellReuseIdentifier:RelationCell];
    self.tableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.stateLabel.hidden = YES;
    footer.refreshingTitleHidden = YES;
    footer.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.automaticallyHidden = YES;
    [self.tableView setSeparatorColor: FCLineColor];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.relations.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return IphonePlus ? 52 : 48;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FCRelationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RelationCell forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    FCRelationModel *relationRequest = self.relations[indexPath.row];
    cell.companyName.text = relationRequest.rel.BrandName ?: relationRequest.rel.Name;
    [cell setContactNumberWithNumber:relationRequest.empCount];
    [cell setStatusStyleWithStatus:relationRequest.status];
    [cell setAreaInfoWithResidentProvince:relationRequest.rel.ResidentProvince ?: @"" ResidentArea:relationRequest.rel.ResidentArea ?: @"" Status:relationRequest.status];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FCRelationModel *relationRequestModel = self.relations[indexPath.row];
    NSDictionary *args = @{
                           @"id": relationRequestModel.Id
                           };
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
//    [SVProgressHUD show];
    WJCWeakSelf
    [FCCustomerRelationRequest getRelationDetailWithArgs:args success:^(id resultObj) {
        FCRelationModel *relationModel = [FCRelationModel mj_objectWithKeyValues:resultObj[@"data"][@"crmSupplyRelationGet"]];
        FCRelationCompanyDetailViewController *relationBindRequestVC = [[FCRelationCompanyDetailViewController alloc] init];
        relationBindRequestVC.relation = relationModel;
        [SVProgressHUD dismiss];
        [weakSelf.navigationController pushViewController:relationBindRequestVC animated:YES];
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
}

-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    [tableView setTableFooterView:view];
}

#pragma mark - 数据加载
- (void)loadNewData{
    NSDictionary *args = @{@"skip": @(0),
                           @"take": @(20),
                           @"model": @(1),
                           @"orderBy": @"status_desc",
                           @"keyword": self.searchTextField.text};
    [self.relations removeAllObjects];
    WJCWeakSelf
    [FCCustomerRelationRequest getRelationRequestsWithArgs:args success:^(id resultObj) {
        FCRelationListModel *body = [FCRelationListModel mj_objectWithKeyValues: resultObj[@"data"][@"crmSupplyRelations"]];
        [weakSelf.relations addObjectsFromArray:body.items];
        MJRefreshAutoNormalFooter *footer = weakSelf.tableView.mj_footer;
        [weakSelf.tableView.mj_header endRefreshing];
        if(weakSelf.relations.count == body.pageInfo.total){
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        } else{
            [weakSelf.tableView.mj_footer resetNoMoreData];
        }
        [weakSelf.tableView reloadData];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView reloadData];
    }];
}
- (void)loadMoreData{
    NSDictionary *args = @{@"skip": @(self.relations.count),
                           @"take": @(20),
                           @"model": @(1),
                           @"orderBy": @"status_desc",
                           @"keyword": self.searchTextField.text};
    WJCWeakSelf
    [FCCustomerRelationRequest getRelationRequestsWithArgs:args success:^(id resultObj) {
        FCRelationListModel *body = [FCRelationListModel mj_objectWithKeyValues: resultObj[@"data"][@"crmSupplyRelations"]];
        
        [weakSelf.relations addObjectsFromArray:body.items];
        if(weakSelf.relations.count == body.pageInfo.total){
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            MJRefreshAutoNormalFooter *footer = weakSelf.tableView.mj_footer;
            return ;
        }
        
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_footer endRefreshing];
    } failure:^(NSError *error) {
        XMGLog(@"%@",error);
        [SVProgressHUD dismiss];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - 获取导航栏黑线
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    
    return nil;
}

@end
